import axios from 'axios'
import router from '../router'
import { config } from '../config/env'

const apiBase = config.apiBase

// 创建不需要认证的axios实例（用于登录、注册、验证码等）
const publicRequest = axios.create({
  baseURL: apiBase,
  timeout: 10000,
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }
})

// 创建需要认证的axios实例
const authRequest = axios.create({
  baseURL: apiBase,
  timeout: 10000,
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }
})

// 为需要认证的请求添加拦截器，自动附加JWT token
authRequest.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    console.log('API请求:', config.method.toUpperCase(), config.url, token ? '有token' : '无token')
    
    if (token) {
      config.headers.Authorization = token
    }
    
    return config
  },
  error => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
const responseInterceptor = {
  success: (response) => {
    console.log('API成功:', response.status)
    const data = response.data
    if (data && typeof data.code !== 'undefined') {
      if (data.code === 403 || data.code === '403') {
        // 未登录或权限问题，跳转登录
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        router.push('/login')
        return Promise.reject(new Error('请先登录'))
      }
      if (data.code === 998 || data.code === '998') {
        // 当日次数用完，抛出特殊错误供调用方显示在气泡中
        return Promise.reject({ limit: true, message: '今日使用次数已达上限，请明日再来！' })
      }
    }
    return data
  },
  error: (error) => {
    console.log('API错误:', error.response?.status, error.response?.statusText)
    if (error.response?.status === 401 || error.response?.status === 403) {
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
}

publicRequest.interceptors.response.use(responseInterceptor.success, responseInterceptor.error)
authRequest.interceptors.response.use(responseInterceptor.success, responseInterceptor.error)

// ========== 不需要认证的接口 ==========
export const getCaptcha = () => {
  return publicRequest.get('/captcha/create')
}

export const getCaptchaImage = (imageUrl) => {
  const encodedUrl = encodeURIComponent(imageUrl)
  return `${apiBase}/captcha/image?url=${encodedUrl}`
}

export const login = (data) => {
  return publicRequest.post('/user/login', data)
}

export const register = (data) => {
  return publicRequest.post('/user/register', data)
}

// 获取用户列表
export const getUserList = () => {
  return publicRequest.get('/user/list')
}

// 查询用户名是否存在
export const getUserName = (username) => {
  return publicRequest.get('/user/exist', { params: { username } })
}

// ========== 需要认证的接口（所有接口都自动带auth，无需手动传token） ==========
export const createChat = () => {
  return authRequest.post('/ai/create')
}

// SSE流式聊天接口
export const createSSEConnection = (url, params, onMessage, onError, onComplete) => {
  const urlParams = new URLSearchParams(params)
  
  const fetchUrl = `${apiBase}${url}?${urlParams}`
  console.log('🔗 SSE连接URL:', fetchUrl)
  console.log('🔗 SSE参数:', params)
  
  const headers = {}
  
  // 使用AbortController来管理连接
  const controller = new AbortController()
  
  fetch(fetchUrl, {
    method: 'GET',
    headers: headers,
    signal: controller.signal
  })
  .then(response => {
    console.log('📡 SSE响应状态:', response.status)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    
    function pump() {
      return reader.read().then(({ done, value }) => {
        if (done) {
          console.log('✅ SSE流读取完成')
          onComplete && onComplete()
          return
        }
        
        const chunk = decoder.decode(value, { stream: true })
        console.log('📥 收到chunk:', JSON.stringify(chunk))
        
        const lines = chunk.split('\n')
        
        for (const line of lines) {
          const trimmedLine = line.trim()
          if (trimmedLine.startsWith('data:')) {
            // 兼容 data: 和 data: 空格
            const data = trimmedLine.startsWith('data: ') ? trimmedLine.slice(6) : trimmedLine.slice(5)
            console.log('📨 提取SSE数据:', data)
            if (data === '[DONE]') {
              console.log('🏁 收到结束标志')
              onComplete && onComplete()
              return
            } else {
              // 不跳过空字符串，全部拼接
              onMessage && onMessage(data)
            }
          } else if (trimmedLine.length > 0) {
            // 兼容后端分片不规范，直接拼接所有非空行
            onMessage && onMessage(trimmedLine)
          }
        }
        
        return pump()
      })
    }
    
    return pump()
  })
  .catch(error => {
    console.log('❌ SSE连接异常:', error)
    
    if (error.message?.includes('403')) {
      window.alert('登录已过期或无权限，请重新登录')
      window.location.href = '/login'
    } else if (error.name === 'AbortError') {
      console.log('🛑 SSE连接被主动中止')
    } else {
      onError && onError(error)
    }
  })
  
  return {
    abort: () => {
      controller.abort()
    }
  }
}

// Manus聊天SSE接口
export const createManusSSEConnection = (message, onMessage, onError, onComplete) => {
  const token = localStorage.getItem('token')
  const params = new URLSearchParams({ message })
  
  const fetchUrl = `${apiBase}/ai/manus/chat?${params}`
  console.log('Manus SSE连接URL:', fetchUrl)
  
  const headers = {}
  
  if (token) {
    headers.Authorization = token
  }
  
  const controller = new AbortController()
  
  fetch(fetchUrl, {
    method: 'GET',
    headers: headers,
    signal: controller.signal
  })
  .then(response => {
    console.log('Manus SSE响应状态:', response.status)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    
    function pump() {
      return reader.read().then(({ done, value }) => {
        if (done) {
          console.log('✅ Manus SSE流读取完成')
          onComplete && onComplete()
          return
        }
        
        const chunk = decoder.decode(value, { stream: true })
        console.log('Manus收到原始chunk:', JSON.stringify(chunk))
        
        const lines = chunk.split('\n')
        
        for (const line of lines) {
          const trimmedLine = line.trim()
          if (trimmedLine.startsWith('data:')) {
            const data = trimmedLine.replace(/^data:\s?/, '')
            console.log('📨 收到Manus SSE数据片段:', data)
            
            if (data === '[DONE]') {
              console.log('✅ Manus SSE传输完成')
              onComplete && onComplete()
              return
            } else if (data && data !== '') {
              onMessage && onMessage(data)
            }
          }
        }
        
        return pump()
      })
    }
    
    return pump()
  })
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Manus SSE连接被中止')
    } else {
      console.error('❌ Manus SSE连接错误:', error)
      onError && onError(error)
    }
  })
  
  return controller
}

export { authRequest }